#include <func.h>
#include "function_c.h"

void judge(int num,int fd,const char* buff)
{
    if(num==0){
        close(fd);
        exit(EXIT_SUCCESS);
    }else if(num<0&&errno!=EINTR){
        perror(buff);
        exit(EXIT_FAILURE);
    }
}

int main(int argc,char* argv[])
{ 
    //./client ip port
    ERROR1(argc,3);
    int port=atoi(argv[2]);
    int clientfd=create_connect(port,argv[1]);
    while(1){
        int ret;
        char buf1[64]={0};
        char buf2[1024]={0};
        char buf[1024]={0};
        char buf3[1024]={0};
        read(STDIN_FILENO,buf,1024);
        sscanf(buf,"%s %s %s",buf1,buf2,buf3);
        int ch=funcjudge(buf1);
        memset(buf,0,1024);
        sprintf(buf,"%d %s %s",ch,buf2,buf3);
        train_t train;
        memset(&train,0,sizeof(train));
        train.length=strlen(buf);
        strcpy(train.buff,buf);
        puts(buf);
        ret=send(clientfd,&train,4+train.length,MSG_WAITALL);
        judge(ret,clientfd,"send");
        if(ret<0&&errno==EINTR) continue;
        switch(ch){
        case CMD_TYPE_EXIT:
            close(clientfd);
            return 0;
            break;
        case CMD_TYPE_CD:
        case CMD_TYPE_PWD:
            memset(buf,0,1024);
            ret=recv(clientfd,buf,1024,0);
            judge(ret,clientfd,"recv");
            if(ret<0&&errno==EINTR) continue;
            puts(buf);
            break;
        case CMD_TYPE_GETSFILE:
            memset(buf,0,1024);
            ret=getsfile_c(clientfd);
            judge(ret,clientfd,"recv");
            if(ret<0&&errno==EINTR) continue;
            break;
        case CMD_TYPE_PUTSFILE:
            memset(buf,0,1024);
            ret=(putsfile_c(clientfd,buf2));
            judge(ret,clientfd,"recv");
            if(ret<0&&errno==EINTR) continue;
            break;
        case CMD_TYPE_LS:
        case CMD_TYPE_LL:
            while(1){
                int length=0;
                ret=recv(clientfd,&length,4,0);
                judge(ret,clientfd,"recv");
                if(ret<0&&errno==EINTR) continue;
                if(length==-1){ 
                    break;
                }
                memset(buf,0,1024);
                ret=recv(clientfd,buf,length,0);
                judge(ret,clientfd,"recv");
                if(ret<0&&errno==EINTR) continue;
                puts(buf);
            } 
            break;
        case CMD_TYPE_MV:
        case CMD_TYPE_CP:
        case CMD_TYPE_RM:
        case CMD_TYPE_MKDIR:
        case CMD_TYPE_RMDIR:
        default:
            break;
        }
        memset(buf,0,1024);
        ret=recv(clientfd,buf,1024,MSG_DONTWAIT);
        if(ret==0) {
            close(clientfd);
            return 0;
        }
        else if(ret>0){
            puts(buf);
        }    
        else if(ret<0&&errno!=EAGAIN&&errno!=EINTR){
            perror("recv");
            exit(1);
        }
    }
}

